﻿using System.Web.Mvc;
using System.Web.Security;
using EpiInfoCloudMagpiBridge.Models;
using Ewav.BAL;
using Ewav.DTO;
using Ewav.Security;

namespace EpiInfoCloudMagpiBridge.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/
        [HttpGet]
        public ActionResult Index()
        {

            EwavUser ewu = new EwavUser();
            ewu.valid = true;


            //ewu.Id = "7A";
            //ewu.Password = "aaaaa";

            //PasswordHasher ph = new PasswordHasher(ConfigurationManager.AppSettings["KeyForUserPasswordSalt"]);

            //string salt = ph.CreateSalt("sagnihotri@cdc.gov");
            //string hash = ph.HashPassword(salt, "3W@ve123");



            return View("Login", ewu);

        }

        public ActionResult LogOff()
        {

            Session.Abandon();
            FormsAuthentication.SignOut();

            // FormsAuthentication.SignOut();
            ApplicationModel.CurrentEwavUserId = "";    


            //  this.Session.Clear();
            
            return RedirectToAction("Index", "Login");

        }

        [HttpPost]
        public ActionResult Authenticate(EwavUser ewu)
        {

            if (ewu.Id == null || ewu.Password == null)
            {

                ewu.valid = false;
                return View("Login", ewu);

            }


            EntityManager em = new EntityManager();

            UserDTO uDto = new UserDTO();
            uDto = em.LoadUser(ewu.Id);

            Cryptography cy = new Cryptography();
            PasswordHasher ph = new PasswordHasher(cy.KeyForUserPasswordSalt);

            string salt = ph.CreateSalt(ewu.Id);

            // Check password        
            if (ph.HashPassword(salt, ewu.Password) == uDto.PasswordHash)
            {
                ApplicationModel.CurrentEwavUserId = ewu.Id;

                //==============================
                FormsAuthentication.SetAuthCookie(ewu.Id, false);
                string UserId = ewu.Id;
                Session["UserId"] = UserId;

                //=============================               
                if (HelperFunctions.UserHasAzureServices() && HelperFunctions.UserHasMagpiServices())
                {
                    return RedirectToAction("Index", "DownloadResponse");

                }
                else
                {
                    return RedirectToAction("Index", "AzureMobileServiceSettings");
                }
            }
            else
            {
                ewu.valid = false;

                return View("Login", ewu);
            }

            //  return View();

        }

    }
}
